package fr.ordre66.vlcs.services;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import fr.ordre66.vlcs.dao.IUploadDao;
import fr.ordre66.vlcs.dto.Upload;

@Service("uploadManager")
public class UploadManager implements IUploadManager{

	@Autowired private IUploadDao uploadDao;
	
	@Override
	public void uploadMedia(Upload upload) {
		if("img".equals(upload.getType())){
			uploadDao.removeOldImg(upload.getLogin());
		}
		upload.setDateOfCreation(new Date());
		uploadDao.uploadMedia(upload);
	}

	@Override
	@Transactional
	public byte[] getLastImage(String login) throws Exception {
		Upload u = uploadDao.getLastImage(login);
		if(u==null)
			throw new Exception();
		return u.getFile().clone();
	}

	@Override
	@Transactional
	public List<Upload> getAllVideos(String login) {
		List<Upload> videosList = uploadDao.getAllVideos(login);
		if(videosList.size() > 4){
			List<Upload> videosSubList = uploadDao.getAllVideos(login).subList(0, 4);
			for(int i=4; i<videosList.size(); i++){
				uploadDao.removeVideo(videosList.get(i).getId().getId());
			}
			return videosSubList;
		}
		return videosList;
	}

	@Override
	@Transactional
	public byte[]  getVideo(String login, long keyID) throws Exception {
		Upload u = uploadDao.getVideo(keyID);
		if(u==null)
			throw new Exception();
		
		if(u.getLogin().equals(login))
			return u.getFile().clone();
		
		return null;
	}

	
}
